#!/bin/bash

# 定义变量
APP_NAME="halo"
JAR_FILE="halo-2.20.19.jar"
LOG_DIR="logs"
PID_FILE="$LOG_DIR/halo.pid"
APP_LOG_FILE="$LOG_DIR/halo-app-stdout.log"
STARTUP_LOG_FILE="$LOG_DIR/halo-startup.log"

# 创建日志目录
mkdir -p "$LOG_DIR"

# 状态检查函数
status() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p $PID > /dev/null; then
    	    echo ""
            echo "$APP_NAME is running (PID: $PID)"
            echo "Uptime: $(ps -p $PID -o etime=)"
            echo "Memory: $(ps -p $PID -o rss=) KB"
            echo ""
            return 0
        else
            echo "$APP_NAME PID file exists but process not found (PID: $PID)"
            return 1
        fi
    else
        echo "$APP_NAME is not running"
        return 3
    fi
}

# 启动函数
start() {
    if status >/dev/null 2>&1; then
        echo "$APP_NAME is already running (PID: $(cat "$PID_FILE"))"
        exit 1
    fi

    echo "Starting $APP_NAME..."
    echo "Startup time: $(date)" >> "$STARTUP_LOG_FILE"
    nohup java -Dfile.encoding=UTF-8 -jar "$JAR_FILE" --spring.config.additional-location=optional:file:./ > "$APP_LOG_FILE" 2>&1 &
    echo $! > "$PID_FILE"
    echo "Started with PID: $!" >> "$STARTUP_LOG_FILE"
    echo "$APP_NAME started (PID: $!)"
}

# 停止函数
stop() {
    if ! status >/dev/null 2>&1; then
        echo "$APP_NAME is not running"
        [ -f "$PID_FILE" ] && rm -f "$PID_FILE"
        exit 1
    fi

    PID=$(cat "$PID_FILE")
    echo "Stopping $APP_NAME (PID: $PID)..."
    echo "Stopped at: $(date)" >> "$STARTUP_LOG_FILE"
    kill $PID
    rm -f "$PID_FILE"
    echo "$APP_NAME stopped"
}

# 根据参数执行相应操作
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        sleep 5
        start
        ;;
    status)
        status
        ;;
    *)
        if status | grep -q "not running"; then
            echo "Usage: $0 {start|stop|restart|status}"
        else
            echo "Usage: $0 {start|stop|restart|status}"
            status
        fi
        exit 1
        ;;
esac

exit $?
